package com.fu.consumer.interceptor;

import com.fu.core.common.BusinessException;
import com.fu.core.common.ExceptionCode;
import com.fu.core.util.RestUtil;
import com.fu.core.util.ThreadLocalUtil;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @author 付龙江
 * @date 2022/1/28 12:11
 */
@Component
public class UserInterceptor implements HandlerInterceptor {
    /**
     * 拦截前处理
     *
     * @param httpServletRequest  request对象
     * @param httpServletResponse response对象
     * @param object              拦截的目标
     * @return 是否放行, true表示放行 ,false表示不放行
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
        System.out.println("进入拦截器");
        //检查是否携带token
        String token = httpServletRequest.getHeader("token");
        if (StringUtils.isEmpty(token)){
            System.out.println("11");
            throw new BusinessException(ExceptionCode.NO_TOKEN);
        }
        String uri = "http://localhost:8090/sso/checkToken";
        MultiValueMap<String, Object> objectObjectLinkedMultiValueMap = new LinkedMultiValueMap<>();
        objectObjectLinkedMultiValueMap.add("token",token);
        Map data = RestUtil.postWithParam(uri, objectObjectLinkedMultiValueMap, Map.class);
        Object user = data.get("data");
        ThreadLocalUtil.setObject(user);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest,
                           HttpServletResponse httpServletResponse,
                           Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest,
                                HttpServletResponse httpServletResponse,
                                Object o, Exception e) throws Exception {
    }
}
